package cn.maiyar.redis.aspect;

import cn.maiyar.redis.annotation.MQPublish;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

/**
 * Redis 消息队列
 *
 * @author c.c
 **/
@Aspect
@Slf4j
@RequiredArgsConstructor
@Component
@ConditionalOnMissingBean(RedissonMqAspect.class)
public class RedissonMqAspect {

    private final RedissonClient redissonClient;

    @Pointcut("@annotation(mqPublish)")
    public void aspect(MQPublish mqPublish) {
    }

    @Around(value = "aspect(mqPublish)", argNames = "proceedingJoinPoint,mqPublish")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint, MQPublish mqPublish) {
        try {
            Object obj = proceedingJoinPoint.proceed();
            RTopic topic = redissonClient.getTopic(mqPublish.name());
            topic.publish(obj);
            return obj;
        } catch (Throwable e) {
            log.error("异常信息:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
